<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN">
<html><head><title>Programming in Lua : 16.1</title>
<link rel="stylesheet" type="text/css" href="pil.css">
</head>
<body>
<p class="warning">
<A HREF="contents.html"><IMG TITLE="Programming in Lua (first edition)" SRC="capa.jpg" ALT="" ALIGN="left"></A>This first edition was written for Lua 5.0. While still largely relevant for later versions, there are some differences.<BR>The third edition targets Lua 5.2 and is available at <A HREF="http://www.amazon.com/exec/obidos/ASIN/859037985X/theprogrammil3-20">Amazon</A> and other bookstores.<BR>By buying the book, you also help to <A HREF="../donations.html">support the Lua project</A>.
</p>
<table width="100%" class="nav">
<tr>
<td width="10%" align="left"><a href="16.html"><img border="0" src="left.png" alt="Previous"></a></td>
<td width="80%" align="center"><a href="contents.html"><font face="Helvetica,Arial,sanserif">
<font color="gray">Programming in </font><font color="blue"> Lua</font>
</font></a></td>
<td width="10%" align="right"><a href="16.2.html"><img border="0" src="right.png" alt="Next"></a></td>
</tr>
<tr>
<td width="10%" align="left"></td>
<td width="80%" align="center"><a href="contents.html#P2">Part II. Tables and Objects</a>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<a href="contents.html#16">Chapter 16. Object-Oriented Programming</a></td>
<td width="10%" align="right"></td></tr>
</table>
<hr/>
<p><h2>16.1 &ndash; Classes</h2>

<p>A <em>class</em> works as a mold for the creation of objects.
Several OO languages offer the concept of class.
In such languages, each object is an instance of a specific class.
Lua does not have the concept of class;
each object defines its own behavior and has a shape of its own.
Nevertheless, it is not difficult to emulate classes in Lua,
following the lead from prototype-based languages,
such as Self and NewtonScript.
In those languages, objects have no classes.
Instead, each object may have a prototype,
which is a regular object where the first object looks up
any operation that it does not know about.
To represent a class in such languages,
we simply create an object to be
used exclusively as a prototype for other objects
(its instances).
Both classes and prototypes work as a place to put behavior to be
shared by several objects.

<p>In Lua, it is trivial to implement prototypes,
using the idea of inheritance that
we saw in the previous chapter.
More specifically, if we have two objects <code>a</code> and <code>b</code>,
all we have to do to make <code>b</code> a prototype for <code>a</code> is
<pre>
    setmetatable(a, {__index = b})
</pre>
After that, <code>a</code> looks up in <code>b</code> for any operation
that it does not have.
To see <code>b</code> as the class of object <code>a</code> is not much
more than a change in terminology.

<p>Let us go back to our example of a bank account.
To create other accounts with behavior similar to <code>Account</code>,
we arrange for these new objects to inherit their operations
from <code>Account</code>, using the <code>__index</code> metamethod.
Note a small optimization, that we do not need to create
an extra table to be the metatable of the account objects;
we can use the <code>Account</code> table itself for that purpose:
<pre>
    function Account:new (o)
      o = o or {}   -- create object if user does not provide one
      setmetatable(o, self)
      self.__index = self
      return o
    end
</pre>
(When we call <code>Account:new</code>,
<code>self</code> is equal to <code>Account</code>;
so we could have used <code>Account</code> directly,
instead of <code>self</code>.
However, the use of <code>self</code> will fit nicely when we introduce
class inheritance, in the next section.)
After that code,
what happens when we create a new account
and call a method on it?
<pre>
    a = Account:new{balance = 0}
    a:deposit(100.00)
</pre>
When we create this new account,
<code>a</code> will have <code>Account</code>
(the <em>self</em> in the call <code>Account:new</code>) as its metatable.
Then, when we call <code>a:deposit(100.00)</code>,
we are actually calling <code>a.deposit(a, 100.00)</code>
(the colon is only syntactic sugar).
However, Lua cannot find a <code>"deposit"</code> entry in table <code>a</code>;
so, it looks into the metatable's <code>__index</code> entry.
The situation now is more or less like this:
<pre>
    getmetatable(a).__index.deposit(a, 100.00)
</pre>
The metatable of <code>a</code> is <code>Account</code>
and <code>Account.__index</code> is also <code>Account</code>
(because the new method did <code>self.__index = self</code>).
Therefore, we can rewrite the previous expression as
<pre>
    Account.deposit(a, 100.00)
</pre>
That is, Lua calls the original <code>deposit</code> function,
but passing <code>a</code> as the <em>self</em> parameter.
So, the new account <code>a</code> inherited the <code>deposit</code> function
from <code>Account</code>.
By the same mechanism,
it can inherit all fields from <code>Account</code>.

<p>The inheritance works not only for methods,
but also for other fields that are absent in the new account.
Therefore, a class provides not only methods,
but also default values for its instance fields.
Remember that, in our first definition of <code>Account</code>,
we provided a field <code>balance</code> with value 0.
So, if we create a new account without an initial balance,
it will inherit this default value:
<pre>
    b = Account:new()
    print(b.balance)    --> 0
</pre>
When we call the <code>deposit</code> method on <code>b</code>,
it runs the equivalent of
<pre>
    b.balance = b.balance + v
</pre>
(because <code>self</code> is <code>b</code>).
The expression <code>b.balance</code> evaluates to zero
and an initial deposit is assigned to <code>b.balance</code>.
The next time we ask for this value,
the index metamethod is not invoked
(because now <code>b</code> has its own <code>balance</code> field).

<hr/>
<table width="100%" class="nav">
<tr valign="top">
<td width="90%" align="left">
<small>
  Copyright &copy; 2003&ndash;2004 Roberto Ierusalimschy.  All rights reserved.
</small>
</td>
<td width="10%" align="right"><a href="16.2.html"><img border="0" src="right.png" alt="Next"></a></td>
</tr>
</table>


</body></html>

